<?php
namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\YuanfenjuService;
use app\common\model\LiuyaoPaipanLog;

/**
 * 六爻排盘接口
 * @ApiWeigh (94)
 */
class LiuyaoPaipan extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';

    /**
     * 六爻排盘
     * 
     * @ApiTitle    (六爻排盘)
     * @ApiSummary  (根据用户信息进行六爻排盘分析)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/liuyao_paipan/index)
     * 
     * @ApiParams   (name="sex", type="integer", required=true, description="性别：0=男，1=女")
     * @ApiParams   (name="born_year", type="integer", required=true, description="公历出生年，如：1988")
     * @ApiParams   (name="pan_model", type="integer", required=true, description="起卦方式：1=自动起卦,2=自选时间,3=终身卦,4=手工指定,5=数字起卦,6=单数起卦,7=双数起卦")
     * @ApiParams   (name="yao_add_time", type="integer", required=false, description="动爻是否加时辰：0=否,1=是", default=0)
     * @ApiParams   (name="year", type="integer", required=false, description="公历起卦年，如：1990")
     * @ApiParams   (name="month", type="integer", required=false, description="公历起卦月，如：8")
     * @ApiParams   (name="day", type="integer", required=false, description="公历起卦日，如：7")
     * @ApiParams   (name="hours", type="integer", required=false, description="公历起卦时，如：12")
     * @ApiParams   (name="minute", type="integer", required=false, description="公历起卦分，如：30")
     * @ApiParams   (name="gua_yao6", type="integer", required=false, description="六爻动静：0=少阴,1=少阳,2=老阴,3=老阳")
     * @ApiParams   (name="gua_yao5", type="integer", required=false, description="五爻动静：0=少阴,1=少阳,2=老阴,3=老阳")
     * @ApiParams   (name="gua_yao4", type="integer", required=false, description="四爻动静：0=少阴,1=少阳,2=老阴,3=老阳")
     * @ApiParams   (name="gua_yao3", type="integer", required=false, description="三爻动静：0=少阴,1=少阳,2=老阴,3=老阳")
     * @ApiParams   (name="gua_yao2", type="integer", required=false, description="二爻动静：0=少阴,1=少阳,2=老阴,3=老阳")
     * @ApiParams   (name="gua_yao1", type="integer", required=false, description="初爻动静：0=少阴,1=少阳,2=老阴,3=老阳")
     * @ApiParams   (name="number", type="integer", required=false, description="指定摇卦数字，如：30")
     * @ApiParams   (name="number_up", type="integer", required=false, description="指定上卦数字，如：2")
     * @ApiParams   (name="number_down", type="integer", required=false, description="指定下卦数字，如：30")
     * @ApiReturn   ({
       "code": 1,
       "msg": "获取成功",
       "time": "1677123456",
       "data": {
         "sex": "男",                      // 性别
         "model": "手工指定",              // 起卦方式
         "gongli": "2024-02-23 17:06:00",  // 公历时间
         "nongli": "二〇二四年正月十四日", // 农历时间
         "nianming": "甲辰",               // 年命
         "has_biangua": "0",               // 是否有变卦
         "dongyao": "0",                   // 动爻位置
         "guashen": "未",                  // 卦身
         "kongwang": "申酉",               // 空亡
         "benqua": "坎为水",               // 本卦
         "benyao": ["九", "六", "六", "六", "九", "六"], // 本卦爻
         "biangua": "坎为水",              // 变卦
         "bianyao": ["九", "六", "六", "六", "九", "六"], // 变卦爻
         "analysis": "..."                 // 卦象分析
       }
     })
     */
    public function index()
    {
        $params = [
            'sex' => $this->request->post('sex', 0, 'intval'),
            'born_year' => $this->request->post('born_year', '', 'intval'),
            'pan_model' => $this->request->post('pan_model', '', 'intval'),
            'yao_add_time' => $this->request->post('yao_add_time', 0, 'intval'),
            'year' => $this->request->post('year', null, 'intval'),
            'month' => $this->request->post('month', null, 'intval'),
            'day' => $this->request->post('day', null, 'intval'),
            'hours' => $this->request->post('hours', null, 'intval'),
            'minute' => $this->request->post('minute', null, 'intval'),
            'gua_yao6' => $this->request->post('gua_yao6', null, 'intval'),
            'gua_yao5' => $this->request->post('gua_yao5', null, 'intval'),
            'gua_yao4' => $this->request->post('gua_yao4', null, 'intval'),
            'gua_yao3' => $this->request->post('gua_yao3', null, 'intval'),
            'gua_yao2' => $this->request->post('gua_yao2', null, 'intval'),
            'gua_yao1' => $this->request->post('gua_yao1', null, 'intval'),
            'number' => $this->request->post('number', null, 'intval'),
            'number_up' => $this->request->post('number_up', null, 'intval'),
            'number_down' => $this->request->post('number_down', null, 'intval')
        ];

        // 必填参数验证
        $required = ['sex', 'born_year', 'pan_model'];
        foreach ($required as $field) {
            if (!isset($params[$field])) {
                $this->error(__('Parameter %s can not be empty', $field));
            }
        }

        // 参数验证
        if (!in_array($params['sex'], [0, 1])) {
            $this->error(__('Invalid sex value'));
        }
        if ($params['pan_model'] < 1 || $params['pan_model'] > 7) {
            $this->error(__('Invalid pan_model value'));
        }

        try {
            $result = YuanfenjuService::instance()->request('/Liupan/liuyao', $params);
            
            if ($result['errcode'] != 0) {
                $this->error($result['errmsg'] ?? '六爻排盘分析失败');
            }
            
            // 记录查询日志
            $logName = sprintf(
                "%s年%s%s", 
                $params['born_year'],
                ['自动', '自选', '终身', '手工', '数字', '单数', '双数'][$params['pan_model'] - 1],
                '起卦'
            );
            
            LiuyaoPaipanLog::create(array_merge(
                $params,
                [
                    'user_id' => $this->auth->id,
                    'name' => $logName,
                    'response_data' => json_encode($result['data'], JSON_UNESCAPED_UNICODE)
                ]
            ));
            
            $this->success('获取成功', $result['data']);
            
        } catch (\think\exception\PDOException $e) {
            $this->error('服务异常：' . $e->getMessage());
        }
    }

    /**
     * 查询历史列表
     * 
     * @ApiTitle    (六爻排盘历史记录)
     * @ApiSummary  (获取用户的六爻排盘查询历史记录)
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/liuyao_paipan/history)
     * @ApiParams   (name="page", type="integer", required=false, description="页码", default=1)
     * @ApiParams   (name="limit", type="integer", required=false, description="每页数量", default=10)
     * 
     * @ApiReturn   ({
       "code": 1,
       "msg": "获取成功",
       "time": "1677123456",
       "data": {
         "total": 100,                     // 总记录数
         "list": [{
           "id": 1,                        // 记录ID
           "name": "1988年手工起卦",       // 记录名称
           "sex": 0,                       // 性别
           "sex_text": "男",               // 性别文字
           "born_year": 1988,              // 出生年
           "pan_model": 4,                 // 起卦方式
           "pan_model_text": "手工指定",   // 起卦方式文字
           "createtime": 1677123456,       // 创建时间戳
           "createtime_text": "2023-02-23 12:34:56" // 创建时间文字
         }]
       }
     })
     */
    public function history()
    {
        $page = $this->request->get('page', 1, 'intval');
        $limit = $this->request->get('limit', 10, 'intval');
        
        $total = LiuyaoPaipanLog::where('user_id', $this->auth->id)->count();
        $list = LiuyaoPaipanLog::where('user_id', $this->auth->id)
            ->field('id,name,sex,born_year,pan_model,createtime')
            ->order('id desc')
            ->page($page, $limit)
            ->select();
        
        $this->success('获取成功', [
            'total' => $total,
            'list' => $list
        ]);
    }

    /**
     * 查询历史详情
     * 
     * @ApiTitle    (六爻排盘历史详情)
     * @ApiSummary  (获取指定六爻排盘记录的详细信息)
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/liuyao_paipan/detail)
     * @ApiParams   (name="id", type="integer", required=true, description="记录ID")
     * 
     * @ApiReturn   ({
        "code": 1,
        "msg": "获取成功",
        "time": "1677123456",
        "data": {
          "id": 1,                          // 记录ID
          "user_id": 1,                     // 用户ID
          "name": "1988年手工起卦",         // 记录名称
          "sex": 0,                         // 性别
          "sex_text": "男",                 // 性别文字
          "born_year": 1988,                // 出生年
          "pan_model": 4,                   // 起卦方式
          "pan_model_text": "手工指定",     // 起卦方式文字
          "yao_add_time": 0,                // 是否加时辰
          "year": null,                     // 起卦年
          "month": null,                    // 起卦月
          "day": null,                      // 起卦日
          "hours": null,                    // 起卦时
          "minute": null,                   // 起卦分
          "gua_yao6": null,                 // 六爻动静
          "gua_yao5": null,                 // 五爻动静
          "gua_yao4": null,                 // 四爻动静
          "gua_yao3": null,                 // 三爻动静
          "gua_yao2": null,                 // 二爻动静
          "gua_yao1": null,                 // 初爻动静
          "number": null,                   // 摇卦数字
          "number_up": null,                // 上卦数字
          "number_down": null,              // 下卦数字
          "createtime": 1677123456,         // 创建时间戳
          "createtime_text": "2023-02-23 12:34:56", // 创建时间文字
          "response_data": {                // 原始接口返回数据
            // ... 同六爻排盘接口返回的data部分
          }
        }
      })
     */
    public function detail()
    {
        $id = $this->request->get('id', 0, 'intval');
        
        $log = LiuyaoPaipanLog::where('user_id', $this->auth->id)
            ->where('id', $id)
            ->find();
            
        if (!$log) {
            $this->error('记录不存在');
        }
        
        $log['response_data'] = json_decode($log['response_data'], true);
        
        $this->success('获取成功', $log);
    }

    /**
     * 清空历史记录
     * 
     * @ApiTitle    (清空六爻排盘历史记录)
     * @ApiSummary  (清空当前用户的所有六爻排盘查询记录)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/liuyao_paipan/clearHistory)
     * 
     * @ApiReturn   ({
     *   "code": 1,
     *   "msg": "清空成功",
     *   "data": null
     * })
     */
    public function clearHistory()
    {
        try {
            LiuyaoPaipanLog::where('user_id', $this->auth->id)->delete();
            $this->success('清空成功');
        } catch (\think\exception\PDOException $e) {
            $this->error('清空失败：' . $e->getMessage());
        }
    }
}